package com.viking.config;

import cn.hutool.json.JSONUtil;
import com.alibaba.csp.sentinel.adapter.gateway.sc.callback.BlockRequestHandler;
import com.alibaba.csp.sentinel.adapter.gateway.sc.callback.GatewayCallbackManager;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeException;
import com.alibaba.csp.sentinel.slots.block.flow.FlowException;
import com.alibaba.csp.sentinel.slots.block.flow.param.ParamFlowException;
import com.alibaba.csp.sentinel.slots.system.SystemBlockException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.web.reactive.function.BodyInserters;
import org.springframework.web.reactive.function.server.ServerResponse;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import javax.annotation.PostConstruct;
import java.util.HashMap;

/**
 * 捕获sentinel熔断异常 处理响应返回  （也可以通过配置文件配置熔断异常信息返回）
 */
@Slf4j
@Configuration
public class GatewaySentinelConfig {

    @PostConstruct
    public void init(){

         BlockRequestHandler blockRequestHandler = new BlockRequestHandler() {
             @Override
             public Mono<ServerResponse> handleRequest(ServerWebExchange exchange, Throwable t) {
                 HashMap<String,Object> map=new HashMap<>();
                 log.info("sentinel熔断异常："+t);
                 System.out.println(JSONUtil.toJsonStr(t));
                 if (t instanceof FlowException) {
                     map.put("code",HttpStatus.TOO_MANY_REQUESTS.value());
                     map.put("message","接口限流了");

                 } else if (t instanceof DegradeException) {
                     map.put("code",HttpStatus.SWITCHING_PROTOCOLS.value());
                     map.put("message","服务降级了");

                 } else if (t instanceof ParamFlowException) {
                     map.put("code",HttpStatus.PROCESSING.value());
                     map.put("message","热点参数限流了");

                 } else if (t instanceof SystemBlockException) {
                     map.put("code",HttpStatus.CHECKPOINT.value());
                     map.put("message","触发系统保护规则了");

                 }
                 // 自定义异常处理
                 return ServerResponse.status(HttpStatus.OK)
                         .contentType(MediaType.APPLICATION_JSON)
                         .body(BodyInserters.fromValue(map));
             }
         };

        GatewayCallbackManager.setBlockHandler(blockRequestHandler);

    }
}
